﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Collections;
using Model;
using Controls;
using UI.ParentForm;
using UI.Common;
using Components;
using UI.Lib;
using UI.Lib.Factory;
using Model.Enum;

namespace UI
{
    public partial class FrmPopWin : BaseForm
    {
        private UI.Common.PopItem popitem = null;
        private Hashtable hsRefData = null;
        StringBuilder scols = null;
        StringBuilder ocols = null;
        private int gridViewHeadWidth = 0; //实际的表格列宽度
        private WinOperate operate = WinOperate.Keyboard;

        private bool _isSelected = false;

        public bool IsSelected
        {
            get { return _isSelected; }
        }

        public FrmPopWin(string _key, Hashtable hs, string word)
        {
            InitializeComponent();

            popitem = PopHelp.GetPopItem(_key, null, hs);
            this.Text = string.IsNullOrEmpty(popitem.Desc) ? this.Text : popitem.Desc;

            this.txtsearch.Text = word;

            //初始化表格
            InitGrid();
            //改变弹出框的大小
            this.Size = new Size(popitem.Width, popitem.Height);
        }

        private void InitGrid()
        {
            PsDataGridViewTextBoxColumn col = null;
            string[] cols = popitem.ShowFields.Split(',');
            if (0 == cols.Length) return;

            scols = new StringBuilder();
            ocols = new StringBuilder();
            string[] sci = null;
            foreach (string s in cols)
            {
                sci = s.Split('|');
                col = new PsDataGridViewTextBoxColumn();
                col.Name = col.OtherName = sci[0];
                col.HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleCenter;
                col.ColType = Model.Enum.PsDataType.String;
                col.HeaderText = sci[2];
                col.DataPropertyName = sci[0];
                col.Visible = (sci.Length < 4 || sci[3] == "y");
                col.Width = col.Visible ? GridViewUtil.Entity.GetHeadWidth(col.HeaderText) : 0;
                gridViewHeadWidth += col.Width;

                if (0 != scols.Length)
                {
                    scols.Append(",");
                    ocols.Append(",");
                }
                scols.Append(string.Format(" ({0}) AS {1} ", sci[1].Replace("&", ","), sci[0]));
                ocols.Append(sci[0]);
                this.dgvMain.Columns.Add(col);

                if (col.Visible == true)
                {
                    //绑定下拉框
                    this.tspSearch.Items.Add(new TextValuePair(col.HeaderText, col.Name));
                }
            }

            if (this.tspSearch.Items.Count > 0) this.tspSearch.SelectedIndex = 0;

            BindGrid();
        }

        /// <summary>
        /// 绑定数据源
        /// </summary>
        private void BindGrid()
        {
            string autoWhere = GetSearchWhere(); //搜索列的值
            //得到popWin的数据
            DataTable dt = CommonHelper.Entity.GetPopData(popitem.Table, scols.ToString(), ocols.ToString(), popitem.OrderFid, popitem.StrWhere, autoWhere, -1);
            if (null == dt) return;

            this.dgvMain.AutoGenerateColumns = false;
            this.dgvMain.DataSource = dt.DefaultView;
        }

        private void dgvMain_CellMouseDoubleClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            if (e.RowIndex < 0) return;

            FillContent(e.RowIndex);
            operate = WinOperate.Mouse;
            _isSelected = true;

            this.Close();
        }

        private void FillContent(int rowIndex)
        {
            if (rowIndex < 0)
            {
                MessageBox.Show("没有行被选中！", "提示");
                return;
            }

            DataGridViewRow dr = this.dgvMain.Rows[rowIndex];

            hsRefData = new Hashtable();

            hsRefData["$SELF$"] = this.dgvMain.Columns.Contains(popitem.KeyRef) ?
                    dr.Cells[popitem.KeyRef].Value : ""; //当前操作弹出框应该返回何字段

            if (string.IsNullOrEmpty(popitem.RefField)) return;

            string[] refFields = popitem.RefField.Split(',');
            string[] ic = null;
            foreach (string item in refFields)
            {
                ic = item.Split('|');
                if (ic.Length < 2) continue;

                if (ic[1].IndexOf("$VALUE$") > -1) //准备将值写入PopWin的Value属性内
                {
                    hsRefData[ic[1]] = this.dgvMain.Columns.Contains(ic[0]) ? dr.Cells[ic[0]].Value : "";
                }
                else
                    hsRefData[ic[1]] = this.dgvMain.Columns.Contains(ic[0]) ? dr.Cells[ic[0]].Value : "";
            }
        }

        public Hashtable GetSelectedData()
        {
            return hsRefData;
        }

        private void tpsOK_Click(object sender, EventArgs e)
        {
            _isSelected = true;

            int idx = (null == this.dgvMain.SelectedRows || this.dgvMain.SelectedRows.Count < 1) ?
                        -1 : this.dgvMain.SelectedRows[0].Index;

            FillContent(idx);

            this.Close();
        }

        private void tspClose_Click(object sender, EventArgs e)
        {
            _isSelected = false;
            this.Close();
        }

        //查询时绑定数据源
        private void tspSearchBtn_Click(object sender, EventArgs e)
        {
            if (!CheckOperate(null == cbxOp.Tag ? Model.Enum.PsDataType.String : (Model.Enum.PsDataType)cbxOp.Tag,
                txtsearch.Text))
            {
                txtsearch.Clear();
                txtsearch.Focus();
                return;
            }

            BindGrid();

            this.dgvMain.Select();
            this.dgvMain.Focus();
        }

        private string GetSearchWhere()
        {
            TextValuePair tv = this.tspSearch.SelectedItem as TextValuePair;
            if (null == tv) return "";
            string value = txtsearch.Text;
            PsDataGridViewTextBoxColumn dc = this.dgvMain.Columns[tv.Value] as PsDataGridViewTextBoxColumn;
            TextValuePair op = this.cbxOp.SelectedItem as TextValuePair;
            if (op == null) return "";

            return SearchHelper.GetSearchWhere(tv, dc, value, op, dc.ColType);
        }

        private void tspSearch_SelectedIndexChanged(object sender, EventArgs e)
        {
            TextValuePair tv = this.tspSearch.SelectedItem as TextValuePair;//当选择的字段名称改变时，重置操作符
            if (tv == null) return;

            string value = txtsearch.Text;
            StringBuilder s = new StringBuilder();
            PsDataGridViewTextBoxColumn dc = this.dgvMain.Columns[tv.Value] as PsDataGridViewTextBoxColumn;
            GetOperateList(dc.ColType, this.cbxOp); //绑定下拉框
        }

        #region 热键相关

        private void BaseMain_Activated(object sender, EventArgs e)
        {
        }

        private void BaseMain_Deactivate(object sender, EventArgs e)
        {
        }

        #endregion

        private void dgvMain_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                operate = WinOperate.Keyboard;

                tpsOK_Click(null, null);
            }
        }

        private void FrmPopWin_Shown(object sender, EventArgs e)
        {
            FrmPopWin_ClientSizeChanged(sender, e);
        }

        private void FrmPopWin_ClientSizeChanged(object sender, EventArgs e)
        {
            //如果单元格的宽度之和小于我的GridView的宽度，则自动填充满
            //this.dgvMain.AutoSizeColumnsMode = //(gridViewHeadWidth < this.dgvMain.ClientSize.Width - 50) ? DataGridViewAutoSizeColumnsMode.Fill :
            //     DataGridViewAutoSizeColumnsMode.None;

            this.dgvMain.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;
        }

        private void FrmPopWin_KeyDown(object sender, KeyEventArgs e)
        {
            switch (e.KeyCode)
            {
                case Keys.End:    //按下的是End == 进入查询 让文本框得到焦点
                    if (this.txtsearch.Visible == true) txtsearch.Focus();
                    break;
                case Keys.Home:    //按下的是Home，Id号为104 == 执行查询
                    if (this.tspSearchBtn.Visible == true) tspSearchBtn_Click(tspSearchBtn, null);
                    break;
                case Keys.Escape:    //按下的是page up，Id号为106 == 返回及关闭
                case Keys.PageUp:
                    this.Close();
                    break;
                case Keys.F4:    //按下的是F4，Id号为107 == 返回及关闭
                    this.Close();
                    break;
                case Keys.F8:    //按下的是F8，Id号为108 == 确定
                    if (tpsOK.Visible == true) tpsOK_Click(null, null);
                    break;
            }
        }

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            this.tsTog.Font = this.dgvMain.Font = Global.AllFont;
            this.dgvMain.ColumnHeadersDefaultCellStyle.Font = Global.AllFont;
            this.dgvMain.RowsDefaultCellStyle.Font = Global.AllFont;
        }

        /// <summary>
        /// 选择项目项的方式
        /// </summary>
        public WinOperate SelectedType { get { return operate; } }

        private void dgvMain_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
        {
            Rectangle rectangle = new Rectangle(e.RowBounds.Location.X,
             e.RowBounds.Location.Y,
             dgvMain.RowHeadersWidth - 4,
             e.RowBounds.Height);

            TextRenderer.DrawText(e.Graphics, (e.RowIndex + 1).ToString(),
                dgvMain.RowHeadersDefaultCellStyle.Font,
                rectangle,
                Color.FromArgb(200, 200, 200),
                TextFormatFlags.VerticalCenter | TextFormatFlags.Right);
        }
    }
}
